/**
 * Main.v8
 * Echo's the 'request' object sent by the server
 **/
var fs = require("fs"),
    path = require("path"),
	out = {
		error: false,
		data: "",
		code: 0
	};

// TODO: Put this in an encrypted JSON file 
var ADP_PASSPHRASE = "password";
	
var Handler = function(req){
	var form = {};
	if (/post/i.test(req.method)){
		form = req.postdata;
	}else{
		form = req.query;
	}
	
    form.timestamp = getTimestamp();
	form.date = getDatestamp();
	var file = "";
    
	if (!form.mode || form.mode === ""){
		// If the mode is blank, default to 'list' view
		if (!req.query.mode || req.query.mode === ""){
			form.mode = "list";
		}else{
			form.mode = req.query.mode;
		}
	}
	
	console.log("\t\t\tView Mode: " + form.mode);
	switch(form.mode){
		case "new":
			// Create new ADP
			if (!checkPassphrase()){
				return out;
			};
			
			delete form.passphrase;
			delete form.mode;
			file = path.join(req.server.assets, "storage", form.school, generateFilename());
			if (checkSchool()){
				saveAsJson();
			};
			
			break;
		case "view":
			// View an existing ADP
			if (!form.adpID || !form.school || form.adpID === "" || form.school === ""){
				out.error = true;
				out.data = "Invalid request.";
				out.code = 500;
				return out;
			}
			
			try{
				out.error = false;
				out.data = require(path.join(req.server.assets, "storage", form.school, form.adpID));
				out.code = 200;
			}catch(e){
				out.error = true;
				out.data = e;
				out.code = 404;
			};
			
			break;
		case "list":
			// List existing ADPs
			if (!form.school){
				out.error = true;
				out.data = "No School Code provided.";
				out.code = 200;
				return out;
			}
			
			try{
				out.error = false;
				out.data = fs.readdirSync(path.join(req.server.docroot, form.school));
				out.code = 200;
			}catch (e){
				out.error = true;
				out.data = e;
				out.code = 500;
			}
			
			
			break;
		case "void":
			// Void an existing ADP
			//		Moves to "void" folder within assets/(school)/ directory
			if (!form.adpID || !form.school || form.adpID === "" || form.school === ""){
				out.error = true;
				out.data = "Invalid request.";
				out.code = 404;
				return out;
			}
			
			if (!checkVoided()){
				return out;
			};
			
			try{
				fs.renameSync(path.join(req.server.assets, "storage", form.school, form.adpID), 
					path.join(req.server.assets, "storage", "void", form.adpID));
				out.error = false;
				out.data = "ADP has been voided.";
				out.code = 200;
			}catch (e){
				out.error = true;
				out.data = e;
				out.code = 500;
			};
			
			break;
		case "schools":
			// Get list of school codes
			console.log("SCHOOL CODES: " + require(path.join(req.server.assets, "school-codes.json")));
			out.error = false;
			out.data = require(path.join(req.server.assets, "school-codes.json"));
			out.code = 200;
			break;
		default:
			out.error = true;
			out.data = "Invalid request.";
			out.code = 500;
			break;
	};
	
	
	function saveAsJson(){
		// Don't overwrite, it shouldn't happen, but JIC
		if (fs.existsSync(file)){
			out.error = true;
			out.data = "ADP '" + file + "' already exists.";
			out.code = 200;
			return out;
		}
		
		
		try{
			fs.writeFileSync(file, JSON.stringify(form, null, "\t"));
			out.error = false;
			out.data = {
				path: file,
				uri: path.basename(file)
			};
			out.code = 200;
			return false;
			
		}catch (err){
			out.error = true;
			out.data = err;
			out.code = 500;
			return false;
		};
	}
	
	function checkPassphrase(){
		if (!form.passphrase || form.passphrase != ADP_PASSPHRASE){
			out.error = true;
			out.data = "Invalid passphrase.";
			out.code = 200;
			return false;
		}
		return true;
	}
	
	function checkSchool(){
		if (!fs.existsSync(path.join(req.server.assets, "storage", form.school))){
			try{
				fs.mkdirSync(path.join(req.server.assets, "storage", form.school));
				return true;
			}catch (e){
				out.error = true;
				out.data = e;
				out.code = 500;
				return false;
			};
		}
		return true;
	}
	
	function checkVoided(){
		if (!fs.existsSync(path.join(req.server.assets, "storage", "void"))){
			try{
				fs.mkdirSync(path.join(req.server.assets, "storage", "void"));
				return true;
			}catch (e){
				out.error = true;
				out.data = e;
				out.code = 500;
				return false;
			};
		}
		return true;
	}
	
	function getDatestamp(){
		var d = new Date();
		return [ d.getMonth()+1, d.getDate(), d.getFullYear() ].join("/");
	}
	
	function getTimestamp(){
		var d = new Date();
		return [ d.getFullYear(), d.getMonth()+1, d.getDate(), "-", d.getHours(), d.getMinutes(), d.getSeconds() ].join("");
	}
	
	function generateFilename(){
		// (date)_(time)-(device).json
		// 03062014-123042_CNU1234567.adp.json 
		return form.device + "-" + form.timestamp + ".adp.json"; 
	}
	
	return out;
};

module.exports.Handler = Handler;